<template>
    <BasicDrawer :treeData="treeData" v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="50%"
        @ok="handleSubmit">
        <BasicForm @register="registerForm" />
    </BasicDrawer>
</template>
<script lang="ts" setup name="UserModal">
import {
    ref, computed, unref, onBeforeMount
} from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from './index-option';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { saveUserApi, updateUserApi } from '/@/api/sys/user';
import { getRoleListApi } from "/@/api/sys/role";
import { useMessage } from '/@/hooks/web/useMessage';
import { getOrgTreeApi } from '/@/api/sys/org';

const { createMessage } = useMessage();
const emit = defineEmits(['success']);
const getTitle = computed(() => (!unref(isUpdate) ? '新增系统用户' : '编辑系统用户'));
const isUpdate = ref(true);
const userId = ref();

const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 80,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { lg: 24, md: 24 },
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    isUpdate.value = !!data?.isUpdate;
    let orgTreeReqResult = await getOrgTreeApi();
    let roleListReqResult = await getRoleListApi()
    updateSchema(
        [
            {
                field: 'password',
                show: !unref(isUpdate)
            },
            {
                field: 'loginName',
                dynamicDisabled: unref(isUpdate)
            },
            {
                field: 'orgId',
                componentProps: { treeData: orgTreeReqResult.data },
            },
            {
                field: 'roleId',
                componentProps: { treeData: roleListReqResult.data },
            }
        ]
    );
    if (unref(isUpdate)) {
        userId.value = data.record.userId;
        setFieldsValue({
            ...data.record,
        });
    } else {
        userId.value = '';
    }
    setDrawerProps({ confirmLoading: false });
});


async function handleSubmit() {
    try {
        const values = await validate();
        setDrawerProps({ confirmLoading: true });
        let res;
        if (unref(isUpdate)) {
            const param = { ...values, userId: userId.value };
            res = await updateUserApi(param);
        } else {
            const param = { ...values, userId: userId.value };
            res = await saveUserApi(param);
        }
        createMessage.success(res.msg);
        closeDrawer();
        emit('success');
    } finally {
        setDrawerProps({ confirmLoading: false });
    }
}
</script>
